<template>
  <div class="p-[5px] flex-1 page_contain" v-loading="pageLoading">
    <el-page-header
      @back="goBack"
      class="mt-[8px] ml-[10px] text-[12px] mb-[6px] page_header"
    >
      <template #content>
        <span class="text-[12px] font-400 mr-3 c-blueGray">
          {{ collectDetail?.equipName || "" }}采集监控详情
        </span>
      </template>
    </el-page-header>
    <div class="page_content">
      <el-row :gutter="0" v-if="collectDetail" class="page_content_row">
        <el-col
          :lg="cardGrid.lg"
          :md="cardGrid.lg"
          :sm="cardGrid.lg"
          :xs="cardGrid.lg"
        >
          <div
            class="bg-#fff m-[5px] !pb-[10px] of-hidden rounded-[8px] produceCard produceCard_left"
          >
            <div>
              <!-- <p class="produce-c-title">
              <svg-icon icon-class="title" />设备基本信息
            </p> -->
              <div class="detail_line pl-[20px] mt-4">
                <div class="detail">
                  <span>设备编号：</span>
                  <span>{{ collectDetail?.equipCode || "" }}</span>
                </div>
                <div class="detail">
                  <span>设备名称：</span>
                  <span>{{ collectDetail?.equipName || "" }}</span>
                </div>
                <div class="detail" v-show="collectDetail?.equipTypeName">
                  <span>设备类型：</span>
                  <span>{{ collectDetail?.equipTypeName || "" }}</span>
                </div>
                <div class="detail">
                  <span>设备型号：</span>
                  <span>{{ collectDetail?.equipCode || "" }}</span>
                </div>
                <div class="detail" v-show="collectDetail?.locationName">
                  <span>位置：</span>
                  <span>{{ collectDetail?.locationName || "" }}</span>
                </div>
                <div class="detail">
                  <span v-if="collectDetail?.equipMonitorStatusName === '报警'">
                    <span
                      class="bg-red w-[13px] h-[13px] rounded-[13px] mt-[7px] mr-[5px]!"
                    ></span
                    >报警</span
                  >
                  <span v-if="collectDetail?.equipMonitorStatusName === '离线'">
                    <span
                      class="bg-gray w-[13px] h-[13px] rounded-[13px] mt-[7px] mr-[5px]!"
                    ></span
                    >离线</span
                  >
                  <span v-else>
                    <span
                      class="bg-[#81B337] w-[13px] h-[13px] rounded-[13px] mt-[7px] mr-[5px]!"
                    ></span
                    >在线</span
                  >
                </div>
              </div>
            </div>
            <div>
              <p class="produce-c-title mt-[25px]!">
                <svg-icon icon-class="title" />监控数据
                <span class="text-[12px] font-400 c-blueGray">
                  （参数类型为整型、浮点和布尔可展示曲线图）
                </span>
              </p>
              <div class="mt-[-5px] check_content">
                <!-- :disabled="!showChartParamTypes.includes(item.parameterType)" -->
                <el-collapse v-if="collectList.length" v-model="activeItems">
                  <el-collapse-item name="1">
                    <template #title>
                      <el-checkbox
                        v-model="checkAll"
                        :indeterminate="isIndeterminate"
                        @click.stop="handleCheckAllChange"
                        class="ml-[15px]"
                      >
                        全部
                      </el-checkbox>
                    </template>
                    <div class="ml-[25px]">
                      <el-checkbox-group
                        v-model="checkParams"
                        @change="handleCheckedsChange"
                      >
                        <el-checkbox
                          v-for="item in collectList"
                          :key="item.id"
                          :label="item.parameterName"
                        >
                          {{ item?.parameterDesc || "" }}
                        </el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>

            <div class="line_chart_div">
              <device-monitor-line-chart
                v-for="checkId in checkParamsShowChart"
                :key="equipCode + checkId"
                :id="equipCode + checkId"
                :isMin="equipCode ? true : false"
                :params="
                collectList.filter((checkItem:any) => checkItem.parameterName === checkId)[0]
              "
                :seriesData="
                  messageContent.filter(
                    (seriesItem) => seriesItem.parameterName === checkId
                  )[0]
                "
              />
            </div>
          </div>
        </el-col>
        <el-col
          :lg="tableGrid.lg"
          :md="tableGrid.lg"
          :sm="tableGrid.lg"
          :xs="tableGrid.lg"
        >
          <div class="bg-[#fff] m-[5px] of-scroll rounded-[8px] produceCard">
            <el-collapse v-if="collectDetail.imgUrl" v-model="activeImages">
              <el-collapse-item title="设备图片" name="1">
                <div class="pt-[0px] px-[12px] flex justify-center">
                  <el-image
                    style="width: 100%"
                    :src="
                      collectDetail.imgUrl
                        ? `${actionUrl}/system/fileCenter/preview/${collectDetail.imgUrl}`
                        : noDevice
                    "
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="
                      collectDetail.imgUrl
                        ? [
                            `${actionUrl}/system/fileCenter/preview/${collectDetail.imgUrl}`,
                          ]
                        : [noDevice]
                    "
                    :initial-index="4"
                    fit="cover"
                  />
                </div>
              </el-collapse-item>
            </el-collapse>

            <div
              class="pb-[5px] overflow-hidden flex flex-wrap items-center w-full"
            >
              <div
                v-for="collect in checkedCollectList"
                :key="collect.id"
                class="w-[50%] collect_info"
              >
                <device-monitor-tag
                  v-if="collect.showType == 2"
                  :id="equipCode + collect.id"
                  :params="collect"
                  :seriesData="
                    messageContent
                      .filter(
                        (seriesItem) =>
                          seriesItem.parameterName === collect.parameterName
                      )[0]
                      ?.parameterValues.slice(-1)[0]
                  "
                />
                <device-monitor-gauge
                  v-if="collect.showType == 1"
                  :id="equipCode + collect.id"
                  :params="collect"
                  :seriesData="
                    messageContent
                      .filter(
                        (seriesItem) =>
                          seriesItem.parameterName === collect.parameterName
                      )[0]
                      ?.parameterValues.slice(-1)[0]
                  "
                />
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<!-- 手动挂载左侧菜单高亮 -->
<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  // 页面进入路由处理
  beforeRouteEnter(to, from, next) {
    to.meta.defaultActive = "/iot/deviceMonitor";
    next();
  },
  // 页面离开路由处理（暂不开发）
  // beforeRouteLeave(to, from, next) {
  //   console.log("from", to);
  //   useTagsViewStore()
  //     .delView(from)
  //     .then((res: any) => {
  //       next();
  //     });
  // },
});
</script>

<script lang="ts" setup>
import request from "@/utils/request";
import noDevice from "@/assets/images/no-device.png";
import dayjs from "dayjs";
import { useRoute, useRouter } from "vue-router";
import { useSocket } from "@/utils/useSocket";
import { MessageContentTS, WSContentTS } from "./index";
import { deepClone } from "@/utils/commonHooks";
import { useTagsViewStore } from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();
const route = useRoute();
const router = useRouter();

defineOptions({
  name: "IOTDEVICEMONITORDETAIL",
  inheritAttrs: false,
});

const props = defineProps({
  equipCode: {
    type: String,
    default: () => {
      return "";
    },
  },
});
const { equipCode } = toRefs(props);

// 图片地址
const actionUrl = import.meta.env.VITE_APP_BASE_API;

// 定义自适应布局
const cardGrid = reactive({
  lg: 16,
  md: 15,
});

const tableGrid = reactive({
  lg: 8,
  md: 9,
});

// 可显示图表的参数类型合集
const showChartParamTypes = ["float", "bool", "integer"];

// 获取采集参数下拉框
const pageLoading = ref(false);
const collectList: any = ref([]);
const collectNameList: any = ref([]);
const collectDetail: any = ref();
const getCollectList = async () => {
  pageLoading.value = true;
  const res: any = await request({
    url: `/iotadmin/deviceMonitor/getDeviceInfo/${
      equipCode.value || route.query.equipCode
    }`,
    method: "get",
  }).catch(() => {
    pageLoading.value = false;
  });
  if (res.code === 200 && res.data) {
    collectDetail.value = res.data;
    collectList.value = res.data?.collectionParamList || [];
    let nameArr: any = [];
    collectList.value?.map((e: any) => {
      nameArr.push(e.parameterName);
    });
    collectNameList.value = nameArr;
    getCollectCookies(); // 获取缓存的回显数据
    initWebSocket("/iotadmin/webSocket/RealTimeMonitor", [res.data?.equipCode]);
  }
  pageLoading.value = false;
};

// 获取 历史缓存 被勾选过的数据
const getCollectCookies = async () => {
  const res: any = await request({
    url: `/iotadmin/scaequipmonitorsetting/getMonitorSetting`,
    method: "post",
    data: {
      equipCode: equipCode.value || route.query.equipCode,
      monitorPage: route.fullPath,
    },
  }).catch(() => {});
  if (res.data) {
    checkParams.value = res.data?.monitorItems ?? [];
  }
};

// 存储 历史缓存 被勾选过的数据
const saveCollectCookies = async () => {
  const res: any = await request({
    url: `/iotadmin/scaequipmonitorsetting/saveMonitorSetting`,
    method: "post",
    data: {
      equipCode: equipCode.value || route.query.equipCode,
      monitorItems: toRaw(checkParams.value),
      monitorPage: route.fullPath,
    },
  }).catch(() => {});
  if (res.data) {
    checkParams.value = res.data;
  }
};

// 采集参数选择逻辑
const checkParams = ref(<any>[]); // 选择v-model数据
const checkParamsShowChart = ref(<any>[]); // 能展示echarts的v-model数据
const checkedCollectList = ref(<any>[]); // 被选择的主体对象

// 监听checkParams，获取checkParamsShowChart
watch(
  () => checkParams.value,
  (newVal) => {
    checkParamsShowChart.value = [];
    checkedCollectList.value = [];
    newVal?.map((item: any) => {
      let a =
        collectList.value.filter(
          (self: any) => self.parameterName === item
        )[0] ?? {};

      if (a?.parameterType) {
        checkedCollectList.value.push(a);
      }

      if (a?.parameterType && showChartParamTypes.includes(a?.parameterType)) {
        checkParamsShowChart.value.push(a?.parameterName);
      }

      console.log("checkedCollectList.value", checkedCollectList.value);
    });
    // 存储被选数据
    saveCollectCookies();
  },
  {
    deep: true,
  }
);

// 全部选择处理逻辑
const checkAll = ref(false);
const isIndeterminate = ref(true);
const handleCheckAllChange = () => {
  checkParams.value = !checkAll.value ? collectNameList.value : [];
  isIndeterminate.value = false;
};

// 单个选择处理逻辑
const handleCheckedsChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === collectNameList.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < collectNameList.value.length;
};

// 返回
const goBack = () => {
  tagsViewStore.delView(route).then((res: any) => {
    router.replace({
      name: "IOTDEVICEMONITOR",
    });
  });
};

// 图片折叠
const activeImages = ref(["1"]);

// 选择项折叠
const activeItems = ref(["1"]);

// 当前页面被激活时触发
onActivated(async () => {
  window.scrollTo(0, 0);
});

const messageContent = ref(<MessageContentTS[]>[]);
// 接受socket消息传递
const dataCallBack = (msg: WSContentTS) => {
  if (msg?.messageType === "internalMessage") {
    const data: MessageContentTS[] = msg?.messageContent;
    let dataResult: MessageContentTS[] = deepClone(messageContent.value) || [];

    // 数据处理 找寻对应匹配的名称 形成messageContent数组中的对象
    data?.map((item: MessageContentTS) => {
      // 筛选返回的数据是否为有效数据
      if (collectNameList.value.includes(item.parameterName)) {
        // 首轮循环push数据
        if (
          !messageContent.value.length ||
          messageContent.value.length < collectNameList.value.length
        ) {
          let obj = {
            ...item,
            parameterValues: [item.parameterValue],
            collectionTimes: [dayjs(item.collectionTime).format("HH:mm:ss")],
          };
          dataResult.push(obj);
        } else {
          // 接受二次数据后，进行数据替换
          const resultIndex = dataResult.findIndex(
            (resultItem: MessageContentTS) =>
              resultItem.parameterName === item.parameterName
          );
          let obj = {
            ...item,
            parameterValues: [
              ...dataResult[resultIndex]?.parameterValues,
              item.parameterValue,
            ],
            collectionTimes: [
              ...dataResult[resultIndex]?.collectionTimes,
              dayjs(item.collectionTime).format("HH:mm:ss"),
            ],
          };
          dataResult[resultIndex] = obj;
        }
      }
    });

    // 限制折线图点数不能超过100
    if (dataResult[0].collectionTimes.length > 100) {
      dataResult.map((self) => {
        self.collectionTimes.shift();
        self.parameterValues.shift();
      });
    }
    messageContent.value = dataResult;
  }
};

// 连接socket & 开启未读消息轮询（2分钟）
const { initWebSocket, websocketclose }: any = useSocket(dataCallBack);
onMounted(() => {
  // 获取设备及采集详情
  if (equipCode.value || route.query.equipCode) {
    getCollectList();
  } else {
    ElMessage.error("设备编号不能为空");
  }
});

onBeforeUnmount(() => {
  websocketclose();
});
</script>

<style lang="scss" scoped>
@media only screen and (max-width: 768px) {
  .el-col-xs-24 {
    padding-right: 10px !important;
  }
}

.produce-c-title {
  font-weight: 600;
  margin: 20px 0 12px 30px;
  font-size: 16px;
  position: RELATIVE;
  padding-left: 15px;
  svg {
    width: 1em;
    height: 1em;
    font-size: 24px;
    transform: rotateZ(-268deg);
    position: absolute;
    left: -11px;
    top: -1px;
  }
}

.numberFont {
  font-family: "DINLight";
  color: #f56c6c;
}
.numberLight {
  font-family: "DINLight";
  font-size: 12px;
  font-weight: 600;
}
.DINLight {
  font-family: "DINLight";
}

// 最新样式
.produceCard {
  height: calc(100vh - 160px);
  overflow-y: auto;
  :deep(.el-collapse) {
    border-top: none;
    .el-collapse-item__header {
      padding: 0 10px;
    }
    .el-collapse-item__content {
      padding-bottom: 15px;
    }
  }
  .check_content {
    :deep(.el-collapse .el-collapse-item__header) {
      height: 38px;
    }
  }
}
:deep(.el-page-header__header) {
  .el-page-header__icon .el-icon {
    color: rgba(148, 163, 184, 1);
    font-size: 14px;
  }
  .el-page-header__back {
    color: rgba(148, 163, 184, 1);
  }
}
.detail_line {
  overflow: hidden;
  .detail {
    font-size: 14px;
    overflow: hidden;
    float: left;
    margin-right: 35px;
    line-height: 28px;
    color: #4e5969;
    span {
      display: block;
      float: left;
      word-break: break-all;
    }
    span:nth-child(1) {
      margin-right: 0px;
    }
  }
}
</style>
